package com.ffcs.cn.action.tableOperator.attrOpenAndLinkage;

import com.ffcs.cn.action.base.dialog.DialogOpenTabular;
import com.supermap.data.DatasetVector;
import com.supermap.desktop.controls.bindView.BindManager;
import com.supermap.desktop.controls.ui.controls.DialogResult;
import com.supermap.desktop.controls.utilities.MapViewUIUtilities;
import com.supermap.desktop.core.Application;
import com.supermap.desktop.core.Interface.IBaseItem;
import com.supermap.desktop.core.Interface.IFormManager;
import com.supermap.desktop.core.Interface.IFormMap;
import com.supermap.desktop.core.Interface.IFormTabular;
import com.supermap.desktop.core.enums.WindowType;
import com.supermap.desktop.core.implement.CtrlAction;
import com.supermap.desktop.core.utilties.FormUtilities;
import com.supermap.desktop.tabularview.FormTabular;

import javax.swing.*;


public class CtrlActionTabularBindMap extends CtrlAction {
	public CtrlActionTabularBindMap(IBaseItem caller) {
		super(caller);
	}

	@Override
	protected void run() {
		IFormManager formManager = Application.getActiveApplication().getMainFrame().getFormManager();
		// 先从打开的窗口获取属性表窗口
		IFormTabular formTabular = null;
		for (int i = 0; i < formManager.getCount(); i++) {
			if (formManager.get(i) instanceof IFormTabular) {
				formTabular = (FormTabular) formManager.get(i);
			}
			if (formTabular != null) {
				break;
			}
		}
		// 如果获取不到属性表窗口，就让用户选择矢量数据集打开一个属性表窗口
		if (formTabular == null) {
			DialogOpenTabular dialogOpenTabular = new DialogOpenTabular();
			dialogOpenTabular.setCheckBoxShowInDialogVisible(false);
			if (dialogOpenTabular.showDialog()== DialogResult.OK) {
				formTabular= dialogOpenTabular.getFormTabular();
			}
		}
		if (formTabular!=null){
			// 将属性表对应矢量数据集打开到新地图窗口
			DatasetVector dataset = formTabular.getDataset();
			IFormMap iFormMap = (IFormMap) FormUtilities.fireNewWindowEvent(WindowType.MAP, dataset.getName() + "@" + dataset.getDatasource().getAlias());
			MapViewUIUtilities.addDatasetsToMap(iFormMap.getMapControl().getMap(),0, dataset);
			// 关联浏览属性表与地图窗口
			BindManager instance = BindManager.getInstance();
			instance.add(formTabular);
			instance.add(iFormMap);
			instance.resetMDILayout();
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					iFormMap.getMapControl().getMap().viewEntire();
				}
			});
		}
	}
}
